import Icon from '@/components/Icons';
import NavBar from '@/components/NavBar';
import {
  clearHistoriesAction,
  clearSuggestsAction,
  getSuggesAction,
  saveHistoriesAction,
} from '@/store/action/scarch';
import { useAppSelector } from '@/store/reducer';
// import classnames from 'classnames';
import { useEffect, useRef, useState } from 'react';
import { useDispatch } from 'react-redux';
import styles from './index.module.scss';

// `innerHTML` 内容防 `XSS` 攻击
import DOMPurify from 'dompurify';

import { Toast } from 'antd-mobile';
import { setLocalHistories } from '@/utils/storage';
import { useHistory } from 'react-router-dom';

//定义处理关键字高亮的方法(正则匹配)
// // keyWord是搜索输入的字段,item是搜素结果
const highlight = (keyWord: string, item: string) => {
  // const reg = new RegExp(keyWord, 'gi');
  // console.log(reg);
  // return item.replace(reg, `<span>$1</span>`);

  // 修复,不能改变大小写的问题
  // 💥 正则中 $1 表示第一个小括号中，匹配到的内容
  const reg = new RegExp(`(${keyWord})`, 'gi');
  return item.replace(reg, `<span>$1</span>`);
};

export default function Search() {
  const inpRef = useRef(-1);
  const [keyWord, setKeyWord] = useState('');
  const dispatch = useDispatch();
  const history = useHistory();

  const { suggestList, histories } = useAppSelector((state) => state.scarch);

  // 最多显示十条历史记录
  const tenHistories = histories.slice(0, 10);

  const handleChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    setKeyWord(e.target.value);

    // 添加事件防抖
    clearTimeout(inpRef.current); //清除延时器
    inpRef.current = window.setTimeout(() => {
      // console.log(e);
      if (!e.target.value.trim()) return;
      dispatch(getSuggesAction(e.target.value));
    }, 200);
  };

  useEffect(() => {
    // 卸载时清除延时器
    return () => {
      clearTimeout(inpRef.current);
      dispatch(clearSuggestsAction());
    };
  }, [dispatch]);

  // 2. keyword为空时，清除搜索建议
  useEffect(() => {
    if (!keyWord) {
      dispatch(clearSuggestsAction());
    }
  }, [keyWord, dispatch]);

  //
  useEffect(() => {
    setLocalHistories(histories);
  }, [histories]);

  // 清除按钮
  const handleClear = () => {
    setKeyWord('');
    // console.log(11);
    dispatch(clearSuggestsAction());
  };

  // 点击搜索保存历史记录
  const handleSearch = () => {
    // 💥细节1: 非空判断
    if (!keyWord.trim()) return Toast.show({ content: '搜索内容不能为空' });
    handleGoToResult(keyWord);
  };

  // 清除搜素历史记录
  const handleClearHistories = () => {
    // 清除reducer
    dispatch(clearHistoriesAction());
    // 清除缓存(因为监听了histories的变化,所以不用写也行)
    // removeLocalHistories();
  };

  // 搜索跳转页面
  const handleGoToResult = (key: string) => {
    // console.log(key);

    // 路由传参的三种方法
    // 动态路由传参方式
    // history.push('/search/result/' + key);

    // 第二参数state传参
    // history.push('/search/result', { keyWord: key });

    // search传递参数
    history.push('/search/result?q=' + key);
    // 保存搜索记录
    dispatch(saveHistoriesAction(key));
  };

  return (
    <div className={styles.root}>
      {/* 顶部导航栏 */}
      <NavBar
        right={
          <span className="search-text" onClick={handleSearch}>
            搜索
          </span>
        }
      >
        <div className="navbar-search">
          <Icon type="iconbtn_search" className="icon-search" />

          <div className="input-wrapper">
            {/* 输入框 */}
            <input
              type="text"
              placeholder="请输入关键字搜索"
              value={keyWord}
              onChange={(e) => handleChange(e)}
              onKeyDown={(e) => e.key === 'Enter' && handleSearch()}
            />

            {/* 清空输入框按钮 */}
            {!!keyWord.trim() && (
              <Icon
                type="iconbtn_tag_close"
                className="icon-close"
                onClick={handleClear}
              />
            )}
          </div>
        </div>
      </NavBar>

      {/* 搜索历史 */}
      {!keyWord.trim() && !!histories.length && (
        <div className="history" style={{ display: 'block' }}>
          <div className="history-header">
            <span>搜索历史</span>
            <span onClick={handleClearHistories}>
              <Icon type="iconbtn_del" />
              清除全部
            </span>
          </div>

          <div className="history-list">
            {tenHistories.map((item, index) => (
              <span
                className="history-item"
                key={index}
                onClick={() => handleGoToResult(item)}
              >
                {item}
                <span className="divider"></span>
              </span>
            ))}
            {/* <span className="history-item">
              Python<span className="divider"></span>
            </span>
            <span className="history-item">
              CSS<span className="divider"></span>
            </span>
            <span className="history-item">
              数据分析<span className="divider"></span>
            </span> */}
          </div>
        </div>
      )}

      {/* 搜素建议结果列表 */}
      <div className="search-result">
        {suggestList.map((item, index) => (
          <div
            className="result-item"
            key={index}
            onClick={() => handleGoToResult(item)}
          >
            <Icon className="icon-search" type="iconbtn_search" />
            <div
              className="result-value"
              // 使用dangerouslySetInnerHTML属性,注入html字符串,解析成Html,类似v-html
              dangerouslySetInnerHTML={{
                __html: DOMPurify.sanitize(highlight(keyWord, item)),
              }}
            >
              {/* {highlight(keyWord, item)} */}

              {/* <span>{'高亮'}</span> */}
              {/* {item.indexOf(keyWord)} */}
              {/* {item.replace(keyWord, `<span>${keyWord}</span>`)} */}
            </div>
          </div>
        ))}
      </div>
    </div>
  );
}
